package com.testplatform.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.testplatform.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.Date;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始执行插入自动填充...");
        // 使用 strictInsertFill 方法，避免覆盖已设置的值
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        
        // 获取当前用户ID，需要结合具体业务（如ThreadLocal、SecurityContext）
        String createAccount = getCurrentUserId();
        this.strictInsertFill(metaObject, "createBy", String.class, createAccount);
        this.strictInsertFill(metaObject, "updateBy", String.class, createAccount);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始执行更新自动填充...");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        String createAccount = getCurrentUserId();
        this.strictUpdateFill(metaObject, "updateUser", String.class, createAccount);
    }
    
    private String getCurrentUserId() {
        String createAccount = SecurityUtils.getUsername();
        // 示例：从ThreadLocal等上下文环境中获取当前登录用户ID
        // 具体实现取决于项目的权限管理框架
        return createAccount; // 实际项目中替换为动态获取的逻辑
    }
}